package com.xz.knowledgeDuplication.thread;

/**
 * 龟兔赛跑
 * @author 召
 * @date 2022-07-18 21:48:31
 */
public class Race implements Runnable{

    /**
     * 胜利者
     */
    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            // 人为让兔子线程睡觉
            if (Thread.currentThread().getName().equals("兔子") && i % 5 == 0) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 判断游戏是否结束
            if (gameOver(i)) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "跑" + i + "步");
        }
    }

    /**
     * 游戏结束
     * @param steps 步
     * @return 游戏是否结束
     */
    private boolean gameOver(int steps) {
        if (winner != null) {
            // 胜利者不为空游戏结束
            return true;
        } else if (steps >= 100) {
            // 到达100步游戏结束
            winner = Thread.currentThread().getName();
            System.out.println("winner is " + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}
